package com.syxd.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.syxd.common.annotation.LogOperation;
import com.syxd.common.constant.Constant;
import com.syxd.common.entity.WebResult;
import com.syxd.common.utils.BeanHelper;
import com.syxd.common.utils.ExcelUtils;
import com.syxd.common.utils.PageData;
import com.syxd.dto.SysJiangCreditContactDto;
import com.syxd.dto.SysJiangCreditDto;
import com.syxd.entity.SysJiangCreditContactEntity;
import com.syxd.entity.SysJiangCreditEntity;
import com.syxd.excel.SysJiangCreditExcel;
import com.syxd.service.SysJiangCreditContactService;
import com.syxd.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务经理对中间联系数据进行操作的接口
 */

@RestController
@RequestMapping("sys/JiangCreditContact")
@Api(tags = "匠信贷临时数据操作")
public class SysJiangCreditContactController {

    @Autowired
    SysJiangCreditContactService sysJiangCreditContactService;
    @Autowired
    SysUserService sysUserService;

    @PostMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.branchName, value = "支行名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "operationType", value = "操作类型", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "processingStatus", value = "审批状态", paramType = "query", dataType = "int")
    })
    @LogOperation(apiType = "sysJiangCreditContact", apiPath = "sys/JiangCreditContact")
    @RequiresPermissions("approval:sysjiang:page")
    public WebResult<PageData<SysJiangCreditContactDto>> page(@ApiIgnore @RequestBody Map<String, Object> params, HttpServletRequest request) {
        String branchName = (String) sysUserService.getInfoFromToken(request, "branchName").getData();
        if (branchName != null) {
            params.put("branchName", branchName);
        }
        PageData<SysJiangCreditContactDto> page = sysJiangCreditContactService.page(params);

        return new WebResult<PageData<SysJiangCreditContactDto>>().ok(page);
    }

    @GetMapping("{id}")
    @LogOperation(apiType = "sysJiangCreditContact", apiPath = "sys/JiangCreditContact")
    @RequiresPermissions("public:sysjiang:page")
    public WebResult query(@PathVariable("id") Long id) {


        return new WebResult().ok(sysJiangCreditContactService.selectById(id));

    }

    @DeleteMapping("{id}")
    @ApiOperation("删除")
    @LogOperation(apiType = "sysJiangCreditContact", apiPath = "sys/JiangCreditContact")
    @RequiresPermissions("public:sysjiang:del:")
    public WebResult delJiangCreditContact(@PathVariable("id") Long id, HttpServletRequest request) {


        return sysJiangCreditContactService.delJiangCreditContact(id, request);


    }

    @PutMapping("update")
    @ApiOperation("修改")
    @LogOperation(apiType = "sysJiangCreditContact", apiPath = "sys/JiangCreditContact")
    @RequiresPermissions("public:sysjiang:update:")
    public WebResult update(@RequestBody SysJiangCreditDto dto, HttpServletRequest request) {
        //效验数据
        return sysJiangCreditContactService.update(dto, request);
    }

    @PutMapping("add")
    @ApiOperation("新增")
    @RequiresPermissions("public:sysjiang:add:")
    public WebResult put(@RequestBody SysJiangCreditDto dto, HttpServletRequest request) {

        return sysJiangCreditContactService.put(dto, request);
    }

    @PostMapping("import")
    @ApiOperation("导入")
    @RequiresPermissions("public:sysjiang:import:")
    public WebResult importJiangList(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());

        ImportParams params = new ImportParams();
        params.setNeedVerify(true);
       // params.setVerfiyGroup(new Class[]{ViliGroupOne.class});
        ExcelImportResult<SysJiangCreditExcel> result = null;
        try {
            result = ExcelImportUtil.importExcelMore(
                    file.getInputStream(),
                    SysJiangCreditExcel.class, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < result.getList().size(); i++) {
            System.out.println(ReflectionToStringBuilder.toString(result.getList().get(i)));
        }
        if(result.getFailList().size()==0){
            List<SysJiangCreditExcel> list = result.getList();
            List<SysJiangCreditContactEntity> sysJiangCreditContactEntities = BeanHelper.copyWithCollection(list, SysJiangCreditContactEntity.class);
            for (SysJiangCreditContactEntity sysJiangCreditContactEntity : sysJiangCreditContactEntities) {
                sysJiangCreditContactEntity.setApplicantId(userId);
                sysJiangCreditContactEntity.setCreateTime(new Date());
                sysJiangCreditContactEntity.setOperationType(Constant.operationType.add.getValue());
                sysJiangCreditContactEntity.setProcessingStatus(Constant.ProcessingStatus.wait.getValue());
                sysJiangCreditContactService.insert(sysJiangCreditContactEntity);
            }
            return new WebResult();
        }
        ArrayList<String> arrayList = new ArrayList<>();
        for (SysJiangCreditExcel sysJiangCreditEntity : result.getFailList()) {

           String msg=  "第"+sysJiangCreditEntity.getRowNum()+ "行"+ sysJiangCreditEntity.getErrorMsg();
           arrayList.add(msg);
        }

         return new WebResult().ok(arrayList);
    }

}
